package com.atming.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;

@Slf4j
@Component
public class ErrorFilter extends ZuulFilter {

    //public  static final Logger logger=LoggerFactory.getLogger(CustomFilter.class);
    //过滤类型
    @Override
    public String filterType() {
        return "error";
    }

    //执行顺序  小 高
    @Override
    public int filterOrder() {
        return 0;
    }

    // 执行条件 true开启
    @Override
    public boolean shouldFilter() {
        return true;
    }

    //动作  具体逻辑
    @Override
    public Object run() throws ZuulException {
        //获取上下文
        RequestContext rc = RequestContext.getCurrentContext();
        Throwable throwable = rc.getThrowable();
        log.error("ErrorFilter..." + throwable.getCause().getMessage(), throwable);

        //相应状态码，HTTP 500 服务器错误
        rc.setResponseStatusCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
        //响应类型
        rc.getResponse().setContentType("application/json; charset=utf-8");
        PrintWriter writer = null;
        try {
            writer = rc.getResponse().getWriter();
            writer.println("{\"message\":\"" + HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase() + "\"}");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != writer) {
                writer.close();
            }
        }

        return null;
    }
}
